import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../../contexts/LanguageContext';
import { useCart } from '../../contexts/CartContext';
import Button from '../../components/Button';
import { useLocalizedLink } from '../../hooks/useLocalizedLink';
import { ShoppingCart, Globe, Calendar, Hash, TrendingDown } from 'lucide-react';
import * as flags from 'country-flag-icons/react/3x2';

type BillingPeriod = 'day' | 'week' | 'month' | 'year';

interface CountryInventory {
  code: string;
  name: string;
  nameCN: string;
  stock: number;
}

// Mock country inventory data
const countryInventory: CountryInventory[] = [
  { code: 'US', name: 'United States', nameCN: '美国', stock: 1234 },
  { code: 'GB', name: 'United Kingdom', nameCN: '英国', stock: 856 },
  { code: 'DE', name: 'Germany', nameCN: '德国', stock: 723 },
  { code: 'FR', name: 'France', nameCN: '法国', stock: 645 },
  { code: 'JP', name: 'Japan', nameCN: '日本', stock: 512 },
  { code: 'CA', name: 'Canada', nameCN: '加拿大', stock: 489 },
  { code: 'AU', name: 'Australia', nameCN: '澳大利亚', stock: 367 },
  { code: 'SG', name: 'Singapore', nameCN: '新加坡', stock: 234 },
  { code: 'NL', name: 'Netherlands', nameCN: '荷兰', stock: 156 },
  { code: 'KR', name: 'South Korea', nameCN: '韩国', stock: 89 },
];

// Base pricing for datacenter IPv6 (per IP)
const basePrices = {
  day: 0.02,
  week: 0.10,
  month: 0.30,
  year: 3.00,
};

// Volume discount tiers
const getDiscountRate = (qty: number): number => {
  if (qty >= 50) return 0.80; // 20% off
  if (qty >= 10) return 0.90; // 10% off
  if (qty >= 5) return 0.95;  // 5% off
  return 1.0; // No discount
};

const PurchaseDatacenterIPv6 = () => {
  const { getLink } = useLocalizedLink();
  const { language } = useLanguage();
  const { addItem } = useCart();
  const navigate = useNavigate();

  // Minimum quantities to meet Stripe's $0.50 minimum payment
  const minimumQuantities = {
    day: 25,    // $0.02 × 25 = $0.50
    week: 5,    // $0.10 × 5 = $0.50
    month: 2,   // $0.30 × 2 = $0.60
    year: 1,    // $3.00 × 1 = $3.00
  };

  // State management
  const [quantity, setQuantity] = useState<number>(minimumQuantities.month);
  const [billingPeriod, setBillingPeriod] = useState<BillingPeriod>('month');
  const [selectedCountry, setSelectedCountry] = useState<string>('US');

  // Calculate total price
  const totalPrice = useMemo(() => {
    const basePrice = basePrices[billingPeriod];
    const discountRate = getDiscountRate(quantity);
    return (basePrice * quantity * discountRate).toFixed(2);
  }, [billingPeriod, quantity]);

  // Calculate unit price after discount
  const unitPrice = useMemo(() => {
    const basePrice = basePrices[billingPeriod];
    const discountRate = getDiscountRate(quantity);
    return (basePrice * discountRate).toFixed(4);
  }, [billingPeriod, quantity]);

  // Calculate discount percentage
  const discountPercentage = useMemo(() => {
    const discountRate = getDiscountRate(quantity);
    return ((1 - discountRate) * 100).toFixed(0);
  }, [quantity]);

  // Get selected country details
  const selectedCountryData = countryInventory.find(c => c.code === selectedCountry);

  const handleAddToCart = () => {
    if (!selectedCountryData) return;
    
    const discountValue = parseFloat(discountPercentage) / 100;
    addItem({
      productType: 'datacenter',
      quantity,
      period: billingPeriod,
      country: selectedCountry,
      countryName: language === 'zh-CN' ? selectedCountryData.nameCN : selectedCountryData.name,
      unitPrice: parseFloat(unitPrice),
      totalPrice: parseFloat(totalPrice),
      ...(discountValue > 0 && { discount: discountValue }),
    });
    navigate(getLink('/cart'));
  };

  // Period labels
  const periodLabels = {
    day: language === 'zh-CN' ? '天' : 'Day',
    week: language === 'zh-CN' ? '周' : 'Week',
    month: language === 'zh-CN' ? '月' : 'Month',
    year: language === 'zh-CN' ? '年' : 'Year',
  };

  // Stock status color
  const getStockColor = (stock: number): string => {
    if (stock > 500) return 'text-green-600 dark:text-green-400';
    if (stock > 100) return 'text-yellow-600 dark:text-yellow-400';
    return 'text-red-600 dark:text-red-400';
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
            {language === 'zh-CN' ? '数据中心 IPv6 选购' : 'Datacenter IPv6 Purchase'}
          </h1>
          <p className="text-lg text-gray-600 dark:text-gray-300">
            {language === 'zh-CN' 
              ? '自定义您的数据中心IPv6代理套餐，享受批量购买折扣'
              : 'Customize your datacenter IPv6 proxy package and enjoy volume discounts'}
          </p>
        </div>

        <div className="grid lg:grid-cols-3 gap-8">
          {/* Configuration Panel */}
          <div className="lg:col-span-2 space-y-6">
            {/* Billing Period Selection */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <div className="flex items-center mb-4">
                <Calendar className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                  {language === 'zh-CN' ? '选择计费周期' : 'Select Billing Period'}
                </h2>
              </div>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                {(Object.keys(basePrices) as BillingPeriod[]).map((period) => (
                  <button
                    key={period}
                    onClick={() => {
                      setBillingPeriod(period);
                      // Reset quantity to minimum when changing billing period
                      setQuantity(minimumQuantities[period]);
                    }}
                    className={`p-4 rounded-lg border-2 transition-all ${
                      billingPeriod === period
                        ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/30 dark:border-blue-400 text-gray-900 dark:text-white'
                        : 'border-gray-200 dark:border-gray-700 hover:border-blue-400 dark:hover:border-blue-500 text-gray-700 dark:text-gray-200'
                    }`}
                  >
                    <div className="text-center">
                      <div className="text-sm font-medium mb-1">
                        {periodLabels[period]}
                      </div>
                      <div className="text-xs text-gray-600 dark:text-gray-400">
                        ${basePrices[period].toFixed(2)}/IP
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>

            {/* Quantity Selection */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center">
                  <Hash className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                  <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                    {language === 'zh-CN' ? '选择IP数量' : 'Select IP Quantity'}
                  </h2>
                </div>
                {parseInt(discountPercentage) > 0 && (
                  <div className="flex items-center text-green-600 dark:text-green-400">
                    <TrendingDown className="w-4 h-4 mr-1" />
                    <span className="text-sm font-semibold">
                      {discountPercentage}% {language === 'zh-CN' ? '折扣' : 'OFF'}
                    </span>
                  </div>
                )}
              </div>

              <div className="space-y-4">
                {/* Slider */}
                <div>
                  <input
                    type="range"
                    min={minimumQuantities[billingPeriod]}
                    max="100"
                    value={quantity}
                    onChange={(e) => setQuantity(parseInt(e.target.value))}
                    className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700 accent-blue-600"
                  />
                  <div className="flex justify-between text-xs text-gray-600 dark:text-gray-400 mt-1">
                    <span>{minimumQuantities[billingPeriod]} IP{minimumQuantities[billingPeriod] > 1 ? 's' : ''}</span>
                    <span>50 IPs</span>
                    <span>100 IPs</span>
                  </div>
                </div>

                {/* Number Input */}
                <div className="flex items-center space-x-4">
                  <input
                    type="number"
                    min={minimumQuantities[billingPeriod]}
                    max="100"
                    value={quantity}
                    onChange={(e) => setQuantity(Math.max(minimumQuantities[billingPeriod], Math.min(100, parseInt(e.target.value) || minimumQuantities[billingPeriod])))}
                    className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '个IP' : 'IPs'}
                  </span>
                </div>

                {/* Quick Select Buttons */}
                <div className="grid grid-cols-4 gap-2">
                  {[1, 5, 10, 50].map((num) => (
                    <button
                      key={num}
                      onClick={() => setQuantity(num)}
                      className={`py-2 rounded-lg text-sm font-medium transition-all ${
                        quantity === num
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                      }`}
                    >
                      {num} {num === 1 ? 'IP' : 'IPs'}
                    </button>
                  ))}
                </div>

                {/* Discount Info */}
                <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-3 text-sm">
                  <div className="text-blue-800 dark:text-blue-300">
                    {language === 'zh-CN' ? '批量购买折扣：' : 'Volume Discounts:'}
                  </div>
                  <ul className="mt-2 space-y-1 text-blue-700 dark:text-blue-400">
                    <li>• 5-9 IPs: 5% {language === 'zh-CN' ? '折扣' : 'off'}</li>
                    <li>• 10-49 IPs: 10% {language === 'zh-CN' ? '折扣' : 'off'}</li>
                    <li>• 50+ IPs: 20% {language === 'zh-CN' ? '折扣' : 'off'}</li>
                  </ul>
                </div>
              </div>
            </div>

            {/* Country Selection */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <div className="flex items-center mb-4">
                <Globe className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                  {language === 'zh-CN' ? '选择国家/地区' : 'Select Country/Region'}
                </h2>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                {countryInventory.map((country) => {
                  const FlagComponent = flags[country.code as keyof typeof flags];
                  return (
                    <button
                      key={country.code}
                      onClick={() => setSelectedCountry(country.code)}
                      className={`p-4 rounded-lg border-2 transition-all text-left ${
                        selectedCountry === country.code
                          ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/30 dark:border-blue-400'
                          : 'border-gray-200 dark:border-gray-700 hover:border-blue-400 dark:hover:border-blue-500'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <div className="w-8 h-5 flex-shrink-0">
                            {FlagComponent && <FlagComponent className="w-8 h-5 rounded shadow-sm" />}
                          </div>
                          <div>
                            <div className="font-medium text-gray-900 dark:text-white">
                              {language === 'zh-CN' ? country.nameCN : country.name}
                            </div>
                            <div className={`text-sm ${getStockColor(country.stock)}`}>
                              {language === 'zh-CN' ? '库存：' : 'Stock: '}{country.stock} IPs
                            </div>
                          </div>
                        </div>
                        {selectedCountry === country.code && (
                          <div className="w-5 h-5 bg-blue-600 rounded-full flex items-center justify-center">
                            <svg className="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
                              <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                            </svg>
                          </div>
                        )}
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Order Summary - Sticky Sidebar */}
          <div className="lg:col-span-1">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 sticky top-20">
              <div className="flex items-center mb-6">
                <ShoppingCart className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                  {language === 'zh-CN' ? '订单摘要' : 'Order Summary'}
                </h2>
              </div>

              <div className="space-y-4 mb-6">
                {/* Product */}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '产品' : 'Product'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {language === 'zh-CN' ? '数据中心 IPv6' : 'Datacenter IPv6'}
                  </span>
                </div>

                {/* Country */}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '国家' : 'Country'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white flex items-center gap-2">
                    {selectedCountryData && (() => {
                      const FlagComponent = flags[selectedCountryData.code as keyof typeof flags];
                      return FlagComponent && <FlagComponent className="w-5 h-3.5 rounded shadow-sm inline-block" />;
                    })()}
                    {language === 'zh-CN' ? selectedCountryData?.nameCN : selectedCountryData?.name}
                  </span>
                </div>

                {/* Quantity */}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '数量' : 'Quantity'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {quantity} {quantity === 1 ? 'IP' : 'IPs'}
                  </span>
                </div>

                {/* Billing Period */}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '计费周期' : 'Billing Period'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {periodLabels[billingPeriod]}
                  </span>
                </div>

                {/* Unit Price */}
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '单价' : 'Unit Price'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    ${unitPrice}/{language === 'zh-CN' ? '个' : 'IP'}
                  </span>
                </div>

                {/* Discount */}
                {parseInt(discountPercentage) > 0 && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600 dark:text-gray-400">
                      {language === 'zh-CN' ? '折扣' : 'Discount'}:
                    </span>
                    <span className="font-medium text-green-600 dark:text-green-400">
                      -{discountPercentage}%
                    </span>
                  </div>
                )}

                <div className="border-t border-gray-200 dark:border-gray-700 pt-4">
                  <div className="flex justify-between items-center">
                    <span className="text-lg font-semibold text-gray-900 dark:text-white">
                      {language === 'zh-CN' ? '总计' : 'Total'}:
                    </span>
                    <span className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                      ${totalPrice}
                    </span>
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-400 text-right mt-1">
                    {language === 'zh-CN' ? `每${periodLabels[billingPeriod]}` : `per ${periodLabels[billingPeriod]}`}
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="space-y-3">
                <Button
                  variant="gradient"
                  size="lg"
                  className="w-full"
                  onClick={handleAddToCart}
                  disabled={!selectedCountryData || selectedCountryData.stock < quantity}
                >
                  <span className="flex items-center justify-center gap-2">
                    <ShoppingCart size={20} />
                    {language === 'zh-CN' ? '加入购物车' : 'Add to Cart'}
                  </span>
                </Button>
                
                {selectedCountryData && selectedCountryData.stock < quantity && (
                  <div className="text-xs text-red-600 dark:text-red-400 text-center">
                    {language === 'zh-CN' 
                      ? `库存不足（仅剩 ${selectedCountryData.stock} 个）`
                      : `Insufficient stock (only ${selectedCountryData.stock} available)`}
                  </div>
                )}

                <Button
                  variant="outline"
                  size="lg"
                  className="w-full"
                  onClick={() => window.location.href = getLink('/pricing/datacenter-ipv6')}
                >
                  {language === 'zh-CN' ? '返回定价页' : 'Back to Pricing'}
                </Button>
              </div>

              {/* Additional Info */}
              <div className="mt-6 text-xs text-gray-500 dark:text-gray-400 space-y-2">
                <p>
                  {language === 'zh-CN' 
                    ? '• 支持多种支付方式'
                    : '• Multiple payment methods supported'}
                </p>
                <p>
                  {language === 'zh-CN' 
                    ? '• 即时开通，无需等待'
                    : '• Instant activation, no waiting'}
                </p>
                <p>
                  {language === 'zh-CN' 
                    ? '• 7天退款保证'
                    : '• 7-day money-back guarantee'}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PurchaseDatacenterIPv6;
